<script setup>
import { ref, onMounted, watch } from 'vue';
import { getCategoryListApi } from '@/apis/pms/category.js'


const props = defineProps({
  categoryId: {
    type: Number,
    default: 0,
  }
})

const emits = defineEmits(['update:categoryId', 'refreshData'])

const defaultProps = {
  label: 'name',
  children: 'children',
}

const categoryTree = ref([])
const getCategoryList = async () => {
  const res = await getCategoryListApi()
  categoryTree.value = res.data
}

const treeRef = ref()
const filterText = ref('')
watch(filterText, (val) => {
  treeRef.value.filter(val)
})

const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}

const handleNodeClick = (data) => {
  if (data.children.length !== 0) {
    return;
  } else {
    emits('update:categoryId', data.id);
    emits('refreshData')
  }
}

onMounted(() => getCategoryList())
</script>

<template>
  <div class="tree">
    <el-input v-model="filterText" placeholder="输入关键词进行过滤" />
    <el-tree ref="treeRef" :data="categoryTree" :props="defaultProps" accordion @node-click="handleNodeClick"
      style="font-size: 16px;" :filter-node-method="filterNode" />
  </div>
</template>

<style scoped lang='scss'>
.tree {
  height: 100%;
  width: 100%;
}
</style>